package com.qiyuesuo.server.filter;

import com.qiyuesuo.server.util.RSA.RSASignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * 拦截器，验证client身份，RSA验签
 *
 * @author s77
 * @create 2020-4月-01 15:07
 */
public class AuthenFilter implements Filter {
    private final static Logger logger = LoggerFactory.getLogger(AuthenFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //演示获取请求头数据：user-agent

        String xsid = ((HttpServletRequest) servletRequest).getHeader("X-SID");
        String xsignature = ((HttpServletRequest) servletRequest).getHeader("X-Signature");
        if (xsid == null || "".equals(xsid) || xsignature == null || "".equals(xsignature)) {
            ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_FORBIDDEN, "Untrusted client");
            return;
        }
        String publicKey = "";
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("publicKey.txt");
        try (Scanner scanner = new Scanner(is)) {
            while (scanner.hasNextLine()) {
                publicKey += scanner.nextLine();
            }
        } catch (Exception e) {
            logger.error("读取公钥文件失败", e);
        }

        if (RSASignature.doCheck(xsid, xsignature, publicKey)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_FORBIDDEN, "Untrusted client");
            return;
        }

    }

    @Override
    public void destroy() {

    }
}
